module ApplicationHelper

  # ------------ user authentication functions ---------------
  def admin?
    if current_user && current_user.role == "admin"
      true
    else
      false
    end
  end
  def iscopeadmin?
    if current_user && (current_user.role == "admin" or current_user.role == "iscopeadmin")
      true
    else
      false
    end
  end
  def owner?(id)
    if current_user.try(:id) == id
      true
    else
      false
    end
  end

  def admin_or_owner?(id=nil)
    if admin? || owner?(id)
      true
    else
      false
    end
  end
  # ----------------- end user authentication functions -----------

  def to_georss(xml, tracks)
    tracks.each { |t|
      unless t.ends_at.nil?
        xml.item do
          xml.title "Track started at #{t.starts_at} by #{t.user.login}"
          desc= "<br/><b>Measurement </b> #{distance_of_time_in_words(t.ends_at, t.starts_at)},  #{(t.city.name unless t.city.nil?)} (gps: #{t.geolocated})<br/> <img src=\"#{t.graph_image_url}\" />"
          desc+="<br/>Tags: </b>#{t.tags.join(",")}"
          desc+= "<br/>Created by <a href=\"/users/#{t.user.id}\"><img src=\"/users/#{t.user.id}.jpg\" width=50 title=\"#{t.user.login}\" /></a>"
          xml.description desc
          xml.author("#{t.user.login})")
          xml.pubDate(t.ends_at.strftime("%a, %d %b %Y %H:%M:%S %z"))
          if (t.geolocated and not t.geom.nil?) #nil check just to sure
            if (RGeo::Feature::Point.check_type(t.geom))
              xml.georss :point do
                xml.text! t.geom.latitude.to_s + ' ' + t.geom.longitude.to_s
              end
            else
              xml.georss :polygon do
                repl = [["LINESTRING", ""],["(",""],[")",""], [",",""]]       #replace wkt to georss simple polygon values
                s = t.geom.exterior_ring.to_s
                repl.each { |r| s = s.gsub(r[0], r[1])  }

                #'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
                  xml.text! s

              end
            end
            #xml << t.geom.georss_simple_representation({:geom_attr=>""})
          end
        end
      end
    }
  end


  # @param [Object] tags
  # @param [Object] s1
  def tag_cloud(tags, s1)
    # zip em
    tags.blank?  ? [] :  tags.zip(s1)
  end

  def generate_kml_measurement_from_point(xml, point)
    geom=point.geom
    xml.Placemark{
      xml.ExtendedData{
        xml.Data(:name=>"decibel"){
          xml.value(point.loudness)
        }
        xml.Data(:name=>"decibel"){
          xml.value(point.loudness)
        }
        #xml.Data(:name=>"geo-corrected"){
        #  xml.value(point.corrected.nil?)
        #}
      }
      xml.styleUrl("#db_index_#{point.loudness_index}")
      xml.Point{
        xml.coordinates("#{geom.lng},#{geom.lat},0")
      }
      xml.TimeStamp{
        xml.when(point.made_at.to_s)
      }
    }
  end

  def generate_kml_measurement(xml, point, shown=1 )
    xml.Placemark{
      xml.visibility(shown)
      xml.ExtendedData{
        xml.Data(:name=>"decibel"){
          xml.value(point["loudness"])
        }
        #xml.Data(:name=>"geo-corrected"){
        #  xml.value(point.corrected.nil?)
        #}
      }
      xml.styleUrl("#db_index_#{point['loudness_index']}")
      xml.Point{
        xml.name("Measure: #{point["loudness"]} db")
        xml.coordinates("#{point['lng']},#{point['lat']},0")
      }
      xml.TimeStamp{
        xml.when(point["made_at"].try(:to_s))
      }
    }
  end

  # generate_kml_grid_measurement - creates a grid for the kml
  def generate_kml_grid_measurement(xml, elm, i)
    xml.Placemark{
      xml.name("Grid #{i}") #name?
      xml.styleUrl("grid_color_#{get_grid_color_index(elm["mean"])}")
      xml.Polygon{
        xml.tesselate(1)
        xml.outerBoundaryIs{
          xml.LinearRing{
            xml.coordinates("#{elm['ymin']},#{elm['xmin']},0 #{elm['ymax']},#{elm['xmin']},0 #{elm['ymax']},#{elm['xmax']},0  #{elm['ymin']},#{elm['xmax']},0 #{elm['ymin']},#{elm['xmin']},0 ")
          }
        }
      }
      xml.ExtendedData{
        xml.Data(:name=>'StdDev'){
          xml.value(elm['stdev'].try(:round, 4))
        }
        xml.Data(:name=>'Max'){
          xml.value(elm['maxdb'])
        }
        xml.Data(:name=> 'Min'){
          xml.value(elm['mindb'])
        }
        xml.Data(:name=> 'Mean'){
          xml.value(elm['mean'].try(:round, 4))
        }
        xml.Data(:name=> 'No. of Measures'){
          xml.value(elm['count'])
        }
      }
      xml.TimeStamp{
        xml.when(elm['made_at'].try(:to_s))
      }
    }
  end


  def style_header(xml, balloon_text, measure_balloon_text)
    colors_table=SoundLevel::COLORS_HTML #if COLORS_HTML is not CONSTANT BUT a FUnction
    SoundLevel.loudness_index_range{ |min, max, idx|
      color=colors_table[idx]
      color="ff"+color[5..6]+color[3..4]+color[1..2]
      #color="ff"+color[1..7]
      xml.Style(:id=>"db_index_#{idx}") {
        xml.IconStyle{
          xml.color(color)
          xml.scale("1")
          xml.Icon{
            xml.href("http://www.google.com/mapfiles/kml/shapes/dot.png")
          }
        }
        xml.BalloonStyle{
          xml.text { |x| x<<balloon_text}
        }
      }
    }
    # aggregate map grip style
    SoundLevel::GRID_COLORS.each_with_index{ |color, idx|
      xml.Style(:id=>"grid_color_#{idx}") {
        xml.LineStyle{
          xml.color(to_kmlcolor(color, "A5")) # 7A - 50% opacity
          xml.width(1)
        }
        xml.PolyStyle{
          xml.color(to_kmlcolor(color, "A5")) #7A - 50% opacity
          xml.fill(true)
        }
        xml.BalloonStyle(:id=> "balloon_style_#{idx}"){
          xml.text { |x| x<<measure_balloon_text}
        }
      }
    }

  end

  def get_icon_style(measure)
  end

  def get_location(measure)
    if measure.corrected.nil?
      measure.geom
    else
      measure.corrected
    end  unless measure.blank?
  end

  # for page titles
  def title(page_title)
    content_for :title, page_title.try(:to_s)
  end
end


# get_grid_color: gets the color of grids of aggregate maps
def get_grid_color(meandb)
    #coloring for the average values of the regions

  case meandb
    when  0..55 then SoundLevel::GRID_COLORS[1]
    when  55..60 then SoundLevel::GRID_COLORS[2]
    when  60..65 then SoundLevel::GRID_COLORS[3]
    when  65..70 then SoundLevel::GRID_COLORS[4]
    when  70..75 then SoundLevel::GRID_COLORS[5]
    when  75..80 then SoundLevel::GRID_COLORS[6]
    when  80..150 then SoundLevel::GRID_COLORS[7]
    else  SoundLevel::GRID_COLORS[0]
  end
end

#return the index of the color in the color array using the mean
def get_grid_color_index(meandb)

  case meandb
    when  0..55 then 1
    when  55..60 then 2
    when  60..65 then 3
    when  65..70 then 4
    when  70..75 then 5
    when  75..80 then 6
    when  80..150 then 7
    else  0
  end

end

# converts hex to kml color i.e.
# Converts the format from #RRGGBB to AABBGGRR.
def to_kmlcolor(color="#000000", alpha = "ff")
  alpha + color[5,3] + color[3,2] + color[1,2]
end

# ----------- utilities --------------

def time_diff(start_time, end_time)
  seconds_diff = (start_time - end_time).to_i.abs

  hours = seconds_diff / 3600
  seconds_diff -= hours * 3600

  minutes = seconds_diff / 60
  seconds_diff -= minutes * 60

  seconds = seconds_diff

  "#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end

